package top.meeting.room.module.system.controllers;

import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.ext.interceptor.GET;
import com.jfinal.ext.interceptor.POST;
import com.jfinal.kit.Kv;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;
import com.jfinal.log.Log4jLog;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import top.jfinal.jwtTokenPlugin.interceptor.AuthInterceptor;
import top.jfinal.jwtTokenPlugin.interceptor.JwtTokenInterceptor;
import top.jfinal.jwtTokenPlugin.kit.JwtKit;
import top.meeting.room.common.base.BaseController;
import top.meeting.room.module.system.form.LoginForm;
import top.meeting.room.module.system.form.RegisterForm;
import top.meeting.room.module.system.form.SetRoleForm;
import top.meeting.room.module.system.form.UserInfoForm;
import top.meeting.room.module.system.model.Role;
import top.meeting.room.module.system.model.User;
import top.meeting.room.module.system.query.UserQuery;
import top.meeting.room.module.system.services.impl.RoleService;
import top.meeting.room.module.system.services.impl.UserService;
import top.meeting.room.module.system.services.impl.WxLoginService;

import java.util.Arrays;

//import top.meeting.room.module.system.services.impl.WxLoginService;

/**
 * 我有故事，你有酒么？
 * JKhaled created by yunqisong@foxmail.com 2017/7/20
 * FOR : 用户API控制
 */
//@Auth(hasForces = {"用户管理"})
@Before({JwtTokenInterceptor.class})
public class UserController extends BaseController {

    private static final Log _log = Log4jLog.getLog(UserController.class);

    /**
     * 获取自己信息方法
     */
    @Before({GET.class})
    @Clear(AuthInterceptor.class)
    public void me() {
        User user = getAttr("me");
        if (user != null) {
            renderJsonSuccess(user == null ? null : user.toMe());
        } else {
            renderError(401);
        }
    }

    /**
     * 登录
     */
    @Before({POST.class})
    @Clear({AuthInterceptor.class, JwtTokenInterceptor.class})
    public void login() {
        LoginForm LoginForm = getJsonParaToObj(LoginForm.class);
        _log.debug("Login by userForm : {}" + String.valueOf(LoginForm));
        String token = JwtKit.getToken(LoginForm.getUserName(), LoginForm.getPassword());
        if (token != null)
            renderJsonSuccess(Kv.by("token", token));
        else
            renderJsonError("用户名或密码错误");
    }

    /**
     * 登录测试API
     */
    @Before({POST.class})
    @Clear({AuthInterceptor.class, JwtTokenInterceptor.class})
    public void testLogin() {
        // TODO:已获取openId
        String openId = getPara("code");
        User userInfo = User.dao.findFirst("select * from t_user where openId = '" + openId + "'");
        if (!StrKit.notNull(userInfo)) {
            RegisterForm registerForm = new RegisterForm();
            registerForm.setUserName("wx" + openId);
            registerForm.setPassword(openId);
            registerForm.setOpenId(openId);
            registerForm.setWxUserId(-1L);
            userInfo = UserService.me.register(registerForm);
        }
        String token = JwtKit.getToken("wx" + openId, openId);
        if (StrKit.isBlank(userInfo.getDepartment()) || StrKit.isBlank(userInfo.getRealName()) || StrKit.isBlank(userInfo.getMobile())) {
            renderJsonError(3, token);
            return;
        }
        if (token != null)
            renderJsonSuccess(Kv.by("token", token));
        else
            renderJsonError("openId无效");
    }


    /**
     * 完善用户信息
     */
    @Before({JwtTokenInterceptor.class})
    public void saveUserInfo() {
        UserInfoForm userInfoForm = getJsonParaToObj(UserInfoForm.class);
        User user = getAttr("me");
        Role role = null;
        if (userInfoForm.getDept().contains("人事") || userInfoForm.getDept().contains("综合")) {
            role = RoleService.me.findByRoleName("综合办");
        }
        UserService.me.updateUserInfo(userInfoForm, user.getId(), role == null ? null : role.getId(), user.getId());
        renderJsonSuccess();
    }

    /**
     * 验证微信登录完成登录
     *
     * @throws Exception
     */
    @Clear
    @Before({Tx.class})
    public void wxLogin() {
        String code = getPara("code");
        if (StrKit.isBlank(code)) {
            renderJsonError("微信认证CODE没有提供");
            return;
        }
        User user = WxLoginService.me.wxLogin(code);
        if (user == null) {
            renderJsonError("微信认证失败");
            return;
        }
        String token = JwtKit.getToken("wx" + user.getOpenId(),
                user.getOpenId());
        if (user.getDepartment() != null) {
            renderJsonSuccess(Kv.by("token", token).set("user", user.toDto()).set("index", true));
            return;
        }
        renderJsonSuccess(Kv.by("token", token).set("user", user.toDto()));
    }

    /**
     * 注册
     */
    @Before({POST.class, Tx.class})
    @Clear({AuthInterceptor.class, JwtTokenInterceptor.class})
    public void register() {
        RegisterForm registerForm = getJsonParaToObj(RegisterForm.class);
        _log.debug("Register by registerForm : {}" + String.valueOf(registerForm));
        User user = UserService.me.register(registerForm);
        if (user != null)
            renderJsonSuccess(user.toDto());
        else
            renderJsonError("注册失败");
    }

    /**
     * 验证用户名是否存在
     */
    @Before({GET.class})
    @Clear({AuthInterceptor.class, JwtTokenInterceptor.class})
    public void isExist() {
        String text = getPara("text");
        _log.debug("IsExist by text : {}" + text);
        Boolean isExist = UserService.me.isExist(text);
        if (isExist)
            renderJsonError("用户名/手机号/邮箱已经被注册过了");
        else
            renderJsonSuccess("用户名/手机号/邮箱可以使用");
    }

    /**
     * 更新 Token
     */
    @Before(POST.class)
    public void refreshToken() {
        String token = getParaToJson().getString("token");
        _log.debug("RefreshToken by token : {}" + token);
        String refreshToken = JwtKit.refreshToken(token);
        if (StrKit.notBlank(refreshToken))
            renderJsonSuccess(Kv.by("token", refreshToken));
        else
            renderJsonError("Token信息不正确");

    }

    /**
     * 禁止直接保存用户
     */
    public void save() {
        renderJsonError("无权访问");
    }

    /**
     * 标记删除用户
     */
    @Before({GET.class, Tx.class})
    public void deletes() {
        String ids = getPara();
        _log.debug("Deletes user by ids : {}" + String.valueOf(ids));
        if (StrKit.notBlank(ids)) {
            UserService.me.deleteByIds(ids);
            renderJsonSuccess();
        } else
            renderJsonError("删除的ID不可以全为空");
    }

    /**
     * 标记恢复用户
     */
    @Before({GET.class, Tx.class})
    public void recoverys() {
        String ids = getPara();
        _log.debug("Recoverys user by ids : {}" + String.valueOf(ids));
        if (StrKit.notBlank(ids)) {
            UserService.me.recoveryByIds(ids);
            renderJsonSuccess();
        } else
            renderJsonError("恢复的ID不可以全为空");
    }

    /**
     * 分配角色
     */
    @Before(POST.class)
    public void setRole() {
        SetRoleForm setRoleForm = getJsonParaToObj(SetRoleForm.class);
        UserService.me.setRole(setRoleForm);
        renderJsonSuccess();
    }


    /**
     * 用户列表
     */
    @Before(GET.class)
    public void find() {
        UserQuery userQuery = getUrlParaToObj(UserQuery.class);
        _log.debug("Find Page<Record(User)> by userQuery : {}" + String.valueOf(userQuery));
        Page<Record> retVal = UserService.me.pageRecord(userQuery);
        if (retVal != null)
            renderJsonSuccess(retVal);
        else
            renderJsonSuccess(Arrays.asList());
    }

    /**
     * 通过ID获取用户
     */
    @Before(GET.class)
    public void get() {
        Long id = getParaToLong();
        _log.debug("Get user by id : {}" + String.valueOf(id));
        if (id != null)
            renderJsonSuccess(UserService.me.getModel(id));
        else
            renderJsonError("查询的ID不可以为空");
    }

    /**
     * 设置审批权
     */
    @Before({GET.class, Tx.class})
    public void setSp() {
        String para = getPara("id");
        if (StrKit.isBlank(para)) {
            renderJsonError("设置审批权的ID不可以为空");
            return;
        }
        Long id = Long.parseLong(para);
        _log.debug("Get user by id : {}" + String.valueOf(id));
        UserService.me.setSp(id);
        renderJsonSuccess();
    }
}
